//
//  ViewController.m
//  jiemeng
//
//  Created by jjl on 13-12-13.
//  Copyright (c) 2013年 jjl. All rights reserved.
//

#import "ViewController.h"
#import "SBJson.h"
#import <QuartzCore/QuartzCore.h>
#import "Reachability.h"
#import "AlertViewHandle.h"
#import "ResultViewController.h"
#define BACKGROUND_COLOR [UIColor colorWithRed:89/255.0 green:54/255.0 blue:34/255.0 alpha:1.0]
#define IS_IOS7 ([UIScreen mainScreen].bounds.size.height >= 528)
@interface ViewController ()
@property (weak, nonatomic  ) IBOutlet UITextField    *nameTextField;
@property (weak, nonatomic  ) IBOutlet UIButton       *jiemengButton;
@property (strong, nonatomic) IBOutlet UIView         *backgroundimage;



@end
@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self isNetwork];
    
    self.nameTextField.delegate          = self;
    self.backgroundimage.backgroundColor = [UIColor blackColor];
    arrayview                            = [[UIView alloc]initWithFrame:CGRectMake(0, 149, 320, 415)];
    NSArray *array                       = [NSArray arrayWithObjects:@"女朋友",@" 打架",@"耳聋",@"蛇",@"怀孕",@"男朋友",@"妻子",@"爱人",@" 杀人",@"自己",@"死人",@"被杀",@"大哭",@"结婚",@"棺材",@"鬼",@"狗",@"家人",nil];
    
    [self.backgroundimage addSubview:arrayview];
    
    tagList                   = [[DWTagList alloc] initWithFrame:CGRectMake(20.0f, 10.0f, 260.0f, 300.0f)];
    tagList.delegate          = self;
    [tagList setTags:array];
    [arrayview addSubview:tagList];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)sendButtonTitle:(NSString *)title
{
    _nameTextField.text = title;
    
    [self jiemengButtonClicked:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)InputSpecification
{
    
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
- (BOOL)prefersStatusBarHidden
{
    return NO;
}
- (IBAction)jiemengButtonClicked:(id)sender
{
    [self isNetwork];
    [self.nameTextField resignFirstResponder];
     [view removeFromSuperview];
  //  [self creatview];
    tishilabel.text=@"";
    if (IS_IOS7)
    {
        scrollview.frame = CGRectMake(10,50,300,480);
    }
    else
    {
        scrollview.frame = CGRectMake(10,50,300,388);
    }

    NSString *str = [NSString stringWithFormat:@"http://api.uihoo.com/dream/dream.http.php?key=%@&format=json", self.nameTextField.text];
    str =  [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url                       = [NSURL URLWithString: str];
    NSMutableURLRequest *request     = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
//    [request setHTTPMethod:@""];//设置请求方式为POST，默认为GET
    
    //将textfile文本框中的内容给服务器
//   NSString *valueStr = [NSString stringWithFormat:@"content=%@",self.nameTextField.text];

//    NSData *data       = [valueStr dataUsingEncoding:NSUTF8StringEncoding];
//    [request setHTTPBody:data];

    NSData *received   = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    //str1 接收返回来的json

    NSString *str1     = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
    
//    if ([str1 rangeOfString:@" "].location != NSNotFound ) {
//             NSString *trimStr = [str1 stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
//    }
//    
   // NSLog(@"str1 is %@",str1);
    
    if ([str1 isEqualToString:@""]||[str1 hasPrefix:@"{"]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"输入信息有误或网络连接断开" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    } else {
   
    //sbjson  解析
   SBJsonParser * parser         = [[SBJsonParser alloc] init];
    NSError * error              = nil;
    NSMutableArray *json = [parser objectWithString:str1 error:&error];
        NSMutableArray *textArray = [[NSMutableArray alloc] init];
        for (int i = 0; i < json.count; i++) {
            if ([[json objectAtIndex:i]rangeOfString:@"\r"].location != NSNotFound) {
                NSString *b = [[json objectAtIndex:i] substringFromIndex:2];
                [json replaceObjectAtIndex:i withObject:b];
            }
        }
        
        for (int i = 0;  i < json.count; i++) {
            if ([[json objectAtIndex:i] rangeOfString:@"<"].location != NSNotFound || [[json objectAtIndex:i]hasPrefix:@"\n"]) {
                NSLog(@"%@",[json objectAtIndex:i]);
                [json removeObjectAtIndex:i];
            }
        }
        
        ResultViewController *resultVC = [[ResultViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:resultVC];
        if (textArray != nil) {
            [resultVC getContentArray:json];
            [self presentViewController:nav animated:NO completion:nil];
        }
       
//    NSMutableArray *array        = [jsonDic objectForKey:@"titles"];
//    NSString *info               =[jsonDic objectForKey:@"info"];
//
//    if(dicUserInfo != (NSString *)[NSNull null] && ![dicUserInfo isEqualToString:@""])
//    {
//        NSString *content  = [[NSString alloc]init];
//        content            = self.nameTextField.text;
//
//
//
////        NSArray *listItems = [str1 componentsSeparatedByString:@"\r\n"];
////
////        //-------拼接
//         NSString *str5     = [json componentsJoinedByString:@""];
////        NSString *str5 = [[NSString alloc] init];
//        
////        
////        for (int i = 0 ; i < json.count; i++) {
////        [str5 stringByAppendingString:[json objectAtIndex:i]];
////        }
//       
//        
//        rcLabel               = [[UILabel alloc]initWithFrame: CGRectZero];
//        [rcLabel setNumberOfLines:0];
//        UIFont *font          = [UIFont fontWithName:@"Arial" size:16];
//        rcLabel.font          = font;
//        rcLabel.textColor     = BACKGROUND_COLOR;
//        rcLabel.lineBreakMode = NSLineBreakByCharWrapping;
//        CGSize size           = CGSizeMake(280,4000);
//        rcLabel.text          = str5;
//        
//        NSDictionary * tdic   = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName,nil];
//        CGSize  actualsize    = [str5 boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:tdic context:nil].size;
//        rcLabel.frame         = CGRectMake(10.0f, 10.0f, 280.0f, actualsize.height);
//    scrollview.contentSize = CGSizeMake(scrollview.frame.size.width, actualsize.height);
//        [scrollview addSubview:rcLabel];
//        
//       
//        if ([content isEqualToString:@""]) {
//            tishilabel.text = @"";
//        }
//        else{
////            tishilabel.text = info;
//        }
//
//    }
//    else
//    {
//      
//        tagList = [[DWTagList alloc] initWithFrame:CGRectMake(10.0f, 10.0f, 260.0f, 280.0f)];
//
////       [tagList setTags:array];
//        tagList.delegate = self;
//     
//        scrollview.contentSize = CGSizeMake(scrollview.frame.size.width, [tagList fittedSize].height);
//        
//       [scrollview addSubview:tagList];
//        
//        }
       
    }
  
}

- (IBAction)as:(id)sender
{
    if (![sender isKindOfClass:[UITextField class]])
    {
        [self.nameTextField resignFirstResponder];
    }
}
-(void)creatview
{
    view=[[UIView alloc]init];
    view.frame=CGRectMake(0, 20, 320, 548);
    view.backgroundColor=[UIColor colorWithRed:239/255.0 green:234/255.0 blue:224/255.0 alpha:1.0];
    [self.backgroundimage addSubview:view];
    UIView *daohangview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    daohangview.backgroundColor=BACKGROUND_COLOR;
    [view addSubview:daohangview];
    
    UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(10, 12, 12, 21)];
    [button setImage:[UIImage imageNamed:@"arrow@2x.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonclick) forControlEvents:UIControlEventTouchUpInside];
    [daohangview  addSubview:button];
    
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(120, 7, 80, 30)];
    label.text=@"搜索结果";
    UIFont *font  = [UIFont fontWithName:@"Arial" size:20];
    label.font    = font;
    label.textColor=[UIColor whiteColor];
    [view addSubview:label];
    scrollview=[[UIScrollView alloc]initWithFrame:CGRectMake(10, 48, 300, 388)];
    scrollview.backgroundColor=[UIColor clearColor];
    [view addSubview:scrollview];
    
    tishilabel=[[UILabel alloc]initWithFrame:CGRectMake(70, 20,180, 30)];
    UIFont *font1  = [UIFont fontWithName:@"Arial" size:18];
    tishilabel.font=font1;
    tishilabel.textColor=BACKGROUND_COLOR;
    [scrollview addSubview:tishilabel];
}
-(void)buttonclick
{
        [view removeFromSuperview];
    
}
-(void)isNetwork
{
    if (![self isConnectionAvailable]) {
        [AlertViewHandle showAlertViewWithMessage:@"网络不给力，请打开3G或Wifi后重试…！"];
    }

}
-(BOOL) isConnectionAvailable{
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach     = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            //NSLog(@"notReachable");
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            //NSLog(@"WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            //NSLog(@"3G");
            break;
    }
    
    return isExistenceNetwork;
}

@end
